import React from 'react'
import styles from './index.module.css'
import {Checkbox, Stepper, Toast} from 'antd-mobile'
import {connect} from "react-redux";
import {withRouter, RouteComponentProps} from 'react-router-dom'
import {Dispatch} from "redux";
import request from "../../utils/request";
import {StateType} from "../../redux/reducers/cart";
import {buySku} from "../../redux/reducers/order";

const CheckboxItem = Checkbox.CheckboxItem;

const ListItem: React.FC<{ item: cartItem, checkboxChange: any, stepChange: any, selectedItems: number[], history: any }>
    = ({item, checkboxChange, stepChange, selectedItems, history}) => {

    return (
        <div className={styles.listItem}>
            <div style={{display: 'flex', alignItems: 'center'}}>
                <CheckboxItem checked={selectedItems.includes(item.cartId)} onChange={checkboxChange}/>
            </div>
            <img src={item.image} alt="" style={{width: '80px', height: '80px'}} onClick={() => {
                history.push(`/product/${item.productId}`)
            }}/>
            <div style={{
                padding: '4px 10px 2px 10px',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-around',
                width: '100%'
            }}>
                <div className={styles.describe}>
                    <b>{item.productName}</b>
                    <span style={{marginTop: '4px'}}>{item.skuFullName}</span>
                </div>
                <div className={styles.compute}>
                    <b style={{marginRight: '10px'}}>¥{item.skuPrice}</b>
                    <Stepper showNumber max={10} min={1} value={item.num} onChange={stepChange}
                             className={styles.stepperClass}/>
                </div>

            </div>
        </div>
    );
};

interface Props extends RouteComponentProps {
    dispatch: Dispatch,
    cart: StateType
}

interface cartItem {
    productId: number,
    productName: string,
    num: number,
    skuId: number,
    cartId: number,
    skuFullName: string,
    skuPrice: number,
    image: string
}


interface States {
    cartList: Array<cartItem>
    checkedAll: boolean
}

class Index extends React.Component<Props, States> {

    state: States = {
        cartList: [],
        checkedAll: false
    };

    componentDidMount() {
        const {cart: {selectedCartList}} = this.props;
        // const checkList = goods.filter((item) => {
        //     return item.checked;
        // });
        //
        // request('/mine/shop-carts').then((result) => {
        //     const {shopCartList}=result;
        // }).catch(() => {
        //
        // });
        // dispatch({
        //     type: 'request-cart-list',
        //     callback: (goods) => {
        //         this.setState({
        //             checkedAll: selectedItems.length === goods.length
        //         });
        //     }
        // });
        request('/cart/list').then((result) => {
            const {cartList} = result.data;
            if (selectedCartList.length === cartList.length) {
                this.setState({
                    checkedAll: true
                });
            }
            this.setState({cartList})
        }).catch(() => {
            Toast.fail('请求失败');
        });
    }


    allToggleCheck = (e: any) => {
        const {dispatch} = this.props;
        const cartIds = this.state.cartList.map((item) => {
            return item.cartId;
        });
        this.setState({
            checkedAll: e.target.checked
        });
        dispatch({
            type: 'cartSelect',
            payload: e.target.checked ? cartIds : []
        });
    };


    collect = () => {
        this.remove();
    };


    remove = () => {
        const {cartList} = this.state;
        const {cart: {selectedCartList}, dispatch} = this.props;
        if (selectedCartList.length === 0) {
            return;
        }
        const newCartList: cartItem[] = [];
        cartList.forEach((item) => {
            if (!selectedCartList.includes(item.cartId)) {
                newCartList.push(item);
            }
        });
        dispatch({
            type: 'cartSelect',
            payload: []
        });
        this.setState({cartList: newCartList, checkedAll: false});
    };


    checkboxChange = (e: any, item: cartItem) => {

        const {cart: {selectedCartList}, dispatch} = this.props;

        if (e.target.checked) {
            selectedCartList.push(item.cartId)
        } else {
            selectedCartList.splice(selectedCartList.indexOf(item.cartId), 1)
        }

        this.setState({
            checkedAll: this.state.cartList.length === selectedCartList.length
        });

        dispatch({
            type: 'cartSelect',
            payload: selectedCartList
        });
        // const {cart: {selectedItems, goods}, dispatch} = this.props;
        // const _this = this;
        // return function (e) {
        //     const newSelectedItems = selectedItems;
        //     if (e.target.checked) {
        //         newSelectedItems.push(item.id)
        //     } else {
        //         newSelectedItems.splice(newSelectedItems.indexOf(item.id))
        //     }
        //     console.log(newSelectedItems);
        //     dispatch(cartAction.toggleCheck(newSelectedItems));
        //
        //     _this.setState({
        //         checkedAll: goods.length === newSelectedItems.length
        //     });
        //
        //     // const checkList = newGoods.filter((item) => {
        //     //     return item.checked;
        //     // });
        //     //
        //     // if (checkList.length === newGoods.length) {
        //     //     _this.setState({
        //     //         checkedAll: true
        //     //     });
        //     // } else {
        //     //     _this.setState({
        //     //         checkedAll: false
        //     //     });
        //     // }
        // }
    };

    stepChange = (changeVal: number, cartItem: cartItem) => {
        console.log('stepChange');
        request('/cart/num', {
            method: 'PUT'
        }).then((result) => {
            this.setState({
                cartList: this.state.cartList.map((item) => {
                    return item.cartId === cartItem.cartId
                        ? {...item, num: changeVal}
                        : item;
                })
            })
        });
    };

    settle = () => {
        const {history, dispatch, cart} = this.props;
        const {cartList} = this.state;

        const selectedSkuList: buySku[] = [];
        cartList.forEach((item, inx) => {
            if (cart.selectedCartList.includes(item.cartId)) {
                selectedSkuList.push({
                    num: item.num,
                    skuId: item.skuId,
                    skuFullName: item.skuFullName,
                    skuPrice: item.skuPrice,
                    productName: item.productName,
                });
            }
        });
        dispatch({
            type: 'checkoutOrder',
            payload: selectedSkuList
        });
        // dispatch({
        //     type: 'orderCheckoutBackUrlSet',
        //     payload: '/',
        // });
        history.push('/order/checkout')
    };

    render() {
        const {cart: {selectedCartList}, history} = this.props;
        const {cartList} = this.state;
        return (
            <div className={styles.container}>
                <div className={styles.header}>
                    <div style={{display: 'flex', alignItems: 'center'}}>

                        <i className={"iconfont icon-shop"} style={{fontSize: '30px'}}/>
                        卧槽商城
                    </div>
                    <div>
                        <b style={{marginRight: '20px'}} onClick={this.collect}>移入收藏</b>
                        <b onClick={this.remove}>删除</b>
                    </div>
                </div>
                <div className={styles.content}>
                    {
                        cartList.map((item, inx) => (
                            <ListItem
                                key={inx}
                                item={item}
                                checkboxChange={(e: any) => {
                                    this.checkboxChange(e, item)
                                }}
                                // @ts-ignore
                                stepChange={(changeVal: any) => {
                                    this.stepChange(changeVal, item)
                                }}
                                selectedItems={selectedCartList}
                                history={history}
                            />
                        ))
                    }
                </div>
                <div className={styles.bottom}>
                    <div style={{
                        display: 'flex',
                        justifyContent: 'space-around',
                        height: '50px',
                        alignItems: 'center'
                    }}>
                        <CheckboxItem onChange={this.allToggleCheck} checked={this.state.checkedAll}>
                            <span style={{fontWeight: 800}}>全选</span>
                        </CheckboxItem>
                        <span className={styles.tips}>不含运费 合计 <b className={styles.money}>¥200.00</b></span>
                        <button className={styles.settleButton} onClick={this.settle}>结算
                        </button>
                    </div>
                </div>
            </div>
        );
    }
}

export default connect((state: Props) => ({cart: state.cart}), (dispatch: Dispatch) =>
    ({dispatch}))(withRouter(Index));
